from . import app_weixin_pay
from conn_mysql import ConnectMysql
from .setting import config
from flask import request, render_template, redirect
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, url_for
from weixin import Weixin, WeixinError
from token_mmwl import Token



weixin = Weixin(config)

@app_weixin_pay.route("/detail_pay")
def pay_html():

    token = request.args.get("token")
    msg = request.args.get('msg')

    if token == None or token == "None" or token == '':

        return redirect(f'/login?msg=登录后才能查看订单情况')

    token_info = Token().token_status(token)

    print(token_info)

    if token_info['status'] == -1:

        return redirect(f"/login?msg={token_info['errorMsg']}")

    else:

        openid = token_info['resultBody']['company_info']['openid']

        consumption_surplus = token_info['resultBody']['company_info']['consumption_surplus']

        with ConnectMysql() as CM:

            sql = "SELECT * FROM prepay WHERE openid=%s and status='SUCCESS' ORDER BY regedate DESC"

            info = CM.select_all(sql, (openid,))

    

        return render_template('detail_pay.html', 
                                token=token, msg=msg, 
                                info=info, consumption_surplus=consumption_surplus)

@app_weixin_pay.route("/jsapi")
def pay_jsapi():
    """微信网页支付请求发起"""
    token = request.args.get('token')
    body = request.args.get('body')
    total_fee = request.args.get('total_fee')

    if token == None or token == 'None':

        return redirect("/login?msg=你没有登录，请登录后付费")

    else:

        token_info = Token().token_status(token)

        if token_info['status'] == -1:

            return redirect(f"/login?msg={token_info['errorMsg']}")

        else:

            openid = token_info['resultBody']['company_info']['openid']

    
    if not all((openid, body, total_fee)):

        return {
                'status': -1,
                'errorCode': '1002',
                'errorMsg': '参数没有到位',
                'resultBody': None
            }

    try:

        out_trade_no = weixin.nonce_str
        raw = weixin.jsapi(openid=openid, body=body, out_trade_no=out_trade_no, total_fee=total_fee)
        # print(raw)#{'package': 'prepay_id=wx131649165306681b1592d03b1839799800', 'appId': 'wx90014a2b7a9ab7f2', 'signType': 'MD5', 'timeStamp': '1586767756', 'nonceStr': 'vBNkDYLmodxPeCVNDz0SAbkyIqXoSK4A', 'sign': '3F950C1AD3FBE2F9551E92BDA406473C'}
        #定单入库
        with ConnectMysql() as conn_obj:

            sql = 'insert into prepay(prepay_id, openid, body, total_fee) values (%s,%s,%s,%s)'
            conn_obj.insert_info(sql, (raw['package'].replace('prepay_id=', ''), openid, body, total_fee))

        # return jsonify(
        #     {
        #         'status': 1,
        #         'errorCode': None,
        #         'errorMsg': None,
        #         'resultBody': raw
        #     }
        # )
        return render_template('pay.html', raw = raw, token =token)


    except WeixinError as e:
        
        return {
                'status': -1,
                'errorCode': '1003',
                'errorMsg': e.args[0],
                'resultBody': None
            }


@app_weixin_pay.route("/notify", methods = ['POST', "GET"])
def pay_notify():
    """
    微信异步通知
    """
    data = weixin.to_dict(request.data)
    with open('pay_notify.log', 'a') as f:
        f.write('\n')
        f.write(str(data))
        f.write('\n')

    openid = data.get('openid')
    sql_preapy_info = 'SELECT * FROM prepay WHERE openid=%s ORDER BY id DESC LIMIT 0,1' 

    with ConnectMysql() as conn_obj:

        preapy_info = conn_obj.select_one(sql_preapy_info, (openid,))#把对应的订单从数据中取来

    preapy_id = preapy_info.get('id')

    #老的订单回调
    if preapy_info.get('status') == "SUCCESS":#判断是否已经交易成功

        return weixin.reply("OK", True)

    elif preapy_info.get('status') == "FAIL":#判断已经交易失败

        return weixin.reply("已经失败", False)


    #新的订单回调
    sql_prepay_status = 'UPDATE prepay SET status=%s WHERE id=%s'#更改prepay状态的sql

    #{'return_code': 'SUCCESS', 'return_msg': 'OK', 'appid': 'wx2421b1c4370ec43b', 'mch_id': '10000100', 'nonce_str': 'IITRi8Iabbblz1Jc', 'openid': 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o', 'sign': '7921E432F65EB8ED0CE9755F0E86D72F', 'result_code': 'SUCCESS', 'prepay_id': 'wx201411101639507cbf6ffd8b0779950874', 'trade_type': 'JSAPI'}
    if not weixin.check(data):#签名验证失败
        with ConnectMysql() as conn_obj:
            conn_obj.update_info(sql_prepay_status, ('FAIL', preapy_id))#更改定单状态为失败
        return weixin.reply("签名验证失败", False)
    
    
    return_code = data.get('return_code')
    result_code = data.get('result_code')

    if result_code == 'SUCCESS' and return_code == 'SUCCESS': #付费成功

        with ConnectMysql() as conn_obj:
            conn_obj.update_info(sql_prepay_status, ('SUCCESS', preapy_id))#更改定单新动态为成功

        total_fee = int(preapy_info.get('total_fee'))#付费金额

        if total_fee == 1:
            add = 1
        elif total_fee == 9900:
            add = 4
        elif total_fee == 20000:
            add = 9

        up_sql = "UPDATE company SET consumption_surplus=consumption_surplus+%s WHERE openid=%s"

        with ConnectMysql() as conn_obj:

            conn_obj.update_info(up_sql, (add, openid))#添加对应次数


        return weixin.reply("OK", True)

    else:#付费失败

        with ConnectMysql() as conn_obj:
            conn_obj.update_info(sql_prepay_status, ('FAIL', prepay_id))#更改定单状态为失败

        return weixin.reply(f"result_code: {result_code},return_code: {return_code}", False)

    